package com.neusoft.actor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neusoft.actor.dao.BedDao;
import com.neusoft.actor.dao.BedUsageDao;
import com.neusoft.actor.dao.CaretakerClientDao;
import com.neusoft.actor.dao.ClientDao;
import com.neusoft.actor.po.*;
import com.neusoft.actor.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClientServiceImpl implements ClientService {

    @Autowired
    private ClientDao clientDao;

    @Autowired
    private CaretakerClientDao caretakerClientDao;

    @Autowired
    private BedUsageDao bedUsageDao;

    @Autowired
    private BedDao bedDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
//    查询所有
    public ResponseBean<List<Client>> getAllClients() {
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_self_care", "自理老人");
        List<Client> clients = clientDao.selectList(queryWrapper);
        return new ResponseBean<>(clients);
    }

    @Override
//    条件查询
    public ResponseBean<List<Client>> getClientsByCondition(String clientName, String isSelfCare) {
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_active", 1);
        if (clientName != null && !clientName.isEmpty()) {
            queryWrapper.like("client_name", clientName);
        }
        if (isSelfCare != null && !isSelfCare.isEmpty()) {
            queryWrapper.eq("is_self_care", isSelfCare);
        }
        List<Client> clients = clientDao.selectList(queryWrapper);
        return new ResponseBean<>(clients);
    }

    @Override
//    条件查询没有管家的客户
    public ResponseBean<List<Client>> getClientsWithoutCaretaker(String clientName) {
//        查询所有有健康管家的客户
        List<CaretakerClient> caretakerClients = caretakerClientDao.selectList(new QueryWrapper<>());
        Set<Client> clients = new HashSet<>();
        for (CaretakerClient caretakerClient : caretakerClients) {
            Client client = clientDao.selectById(caretakerClient.getClientId());
            clients.add(client);
        }

//        查询所有客户
        List<Client> allClients = clientDao.selectList(new QueryWrapper<>());
        List<Client> clientsWithoutCaretaker = new ArrayList<>();
        for (Client client : allClients) {
            boolean belongsToCare = false;
            for (Client c : clients) {
                if (c.getClientId().equals(client.getClientId())) { // 比较 id 字段
                    belongsToCare = true;
                    break;
                }
            }
            if (!belongsToCare) {
                if (clientName != null && !clientName.isEmpty()) {
                    if (clientName.equals(client.getClientName())) {
                        clientsWithoutCaretaker.add(client);
                    }
                } else {
                    clientsWithoutCaretaker.add(client);
                }
            }
        }
        if (!clientsWithoutCaretaker.isEmpty()) {
            return new ResponseBean<>(clientsWithoutCaretaker);
        } else {
            return new ResponseBean<>(404, "未找到没有配置管家的客户");
        }
    }

    @Override
//    查询健康管家管理的客户，可根据客户名模糊查询
    public ResponseBean<List<Client>> getClientsByCaretaker(Integer caretakerId, String clientName) {
//        查询所有有健康管家的客户
        List<CaretakerClient> caretakerClients = caretakerClientDao.selectList(new QueryWrapper<CaretakerClient>().eq("caretaker_id", caretakerId));
        List<Client> clients = new ArrayList<>();
        for (CaretakerClient caretakerClient : caretakerClients) {
            Client client = clientDao.selectById(caretakerClient.getClientId());
            clients.add(client);
        }

        // 如果提供了客户名称，则进行模糊查询
        if (clientName != null && !clientName.isEmpty()) {
            clients = clients.stream()
                    .filter(client -> client.getClientName().contains(clientName))
                    .collect(Collectors.toList());
        }

        // 返回结果
        if (!clients.isEmpty()) {
            return new ResponseBean<>(clients);
        } else {
            return new ResponseBean<>(404, "客户未找到");
        }
    }

    @Override
    public ResponseBean<Client> getClientById(Integer clientId) {
        Client client = clientDao.selectById(clientId);
        if (client != null) {
            return new ResponseBean<>(client);
        } else {
            return new ResponseBean<>(404, "客户未找到");
        }
    }

    @Override
    public ResponseBean<Client> getClientByName(String clientName) {
        Client client = clientDao.selectOne(new QueryWrapper<Client>().eq("client_name", clientName));
        if (client != null) {
            return new ResponseBean<>(client);
        } else {
            return new ResponseBean<>(404, "客户未找到");
        }
    }

    @Override
    public ResponseBean<Integer> addClient(Client client) {
        int result = clientDao.insert(client);

//        安排床
        Bed bed = bedDao.selectOne(new QueryWrapper<Bed>().eq("room_number", client.getRoomNumber()).eq("bed_number", client.getBedNumber()));
        bed.setStatus("有人");
        bedDao.updateById(bed);

//        添加床位使用记录
        BedUsage bedUsage = new BedUsage();
        bedUsage.setClientId(client.getClientId());
        bedUsage.setBedId(bed.getBedId());
        bedUsage.setStartDate(client.getAdmissionDate());
        bedUsage.setEndDate(client.getContractExpiry());
        bedUsage.setIsCurrent(true);
        bedUsageDao.insert(bedUsage);

        if (result > 0) {
            return new ResponseBean<>(result); // 返回插入成功的行数
        } else {
            return new ResponseBean<>(500, "客户添加失败");
        }
    }

    @Override
    public ResponseBean<Integer> updateClient(Client client) {
        int result = clientDao.updateById(client);
        if (result > 0) {
            return new ResponseBean<>(result); // 返回更新成功的行数
        } else {
            return new ResponseBean<>(500, "客户信息更新失败");
        }
    }

    @Override
    public ResponseBean<Integer> deleteClient(Integer clientId) {
        int result = clientDao.deleteById(clientId);
        if (result > 0) {
            return new ResponseBean<>(result); // 返回删除成功的行数
        } else {
            return new ResponseBean<>(500, "客户删除失败");
        }
    }
}